package org.zxy.auth.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.zxy.auth.domain.Permission;
import org.zxy.auth.domain.Role;
import org.zxy.auth.domain.RolePermission;
import org.zxy.auth.dto.RoleDto;
import org.zxy.auth.mapper.PermissionMapper;
import org.zxy.auth.mapper.RolePermissionMapper;
import org.zxy.auth.service.IRoleService;
import org.zxy.base.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zxy
 * @since 2024-04-09
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void saveOrUpdate(RoleDto roleDto) {
        //role中的数据在角色表中
        //permissionIds数据在角色权限中间表中
        Role role = roleDto.getRole();
        if (role.getId() != null) {
            super.update(role);
        } else {
            super.insert(role);
        }
        List<Permission> permissions = permissionMapper.queryByIds(roleDto.getPermissionIds());
        List<RolePermission> list = new ArrayList<>();
        for (Permission permission : permissions) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(role.getId());
            rolePermission.setPermissionId(permission.getId());
            rolePermission.setPermissionSn(permission.getSn());
            list.add(rolePermission);
        }
        rolePermissionMapper.batchSave(list);
    }

    @Override
    public List<Long> getPermsssionId(Long id) {
        return rolePermissionMapper.getPermsssionId(id);
    }
}
